# from app import mail, sender
from flask import current_app, Flask
from flask.cli import with_appcontext
from flask_mail import Message, Mail
from random import randint
import threading
import redis


class MailUtil:

    # 发送信息
    @staticmethod
    @with_appcontext
    def send(emails, body, html=None):
        try:
            mail = current_app.mail
            sender = current_app.sender
            mail.send(Message(sender=('lxh网站', sender), body=body, recipients=emails, html=html))
        except Exception as e:
            print('发送消息出现了异常', e)
        pass

    @staticmethod
    def sendCode(emails):
        try:
            sender = current_app.sender
            ThreadMail(sender, emails).start()
        except Exception as e:
            print('发送消息出现了异常', e)
        pass


# 产生验证码
class CodeUtil:
    @staticmethod
    def createCode():
        result = ""
        for i in range(4):
            num = randint(0, 9)
            result += str(num)
        return result


class RedisUtil:

    @staticmethod
    def connect():
        connect = redis.Redis()
        return connect

    @staticmethod
    def setKey(key, value):
        con = RedisUtil.connect()
        con.set(key, value=value)

    @staticmethod
    def getKey(key):
        con = RedisUtil.connect()
        return con.get(key)


class ThreadMail(threading.Thread):
    def __init__(self, sender, emails):
        threading.Thread.__init__(self)
        app = Flask(__name__)
        app.config['JSON_AS_ASCII'] = False
        app.config['MAIL_SERVER'] = 'smtp.qq.com'
        app.config['MAIL_PORT'] = 465
        app.config['MAIL_USERNAME'] = sender
        app.config['MAIL_PASSWORD'] = 'ibvhkyppalvuieeb'
        app.config['MAIL_USE_TLS'] = False
        app.config['MAIL_USE_SSL'] = True
        self.mail = Mail(app)
        self.sender = sender
        self.emails = emails
        print("创建了，这是app", app)
        self.app = app

    def run(self) -> None:
        for oneEmail in self.emails:
            code = CodeUtil.createCode()
            RedisUtil.setKey("lxhEmail" + oneEmail, code)
            subject = "验证码发送"
            html = "<p>" \
                   "尊敬的用户您好：<br />" \
                   "欢迎你进行注册lxh网站，您此次的验证码为:" + "<h2>" + code + "</h2></p>"
            with self.app.app_context():
                self.mail.send(Message(subject, sender=('lxh网站', self.sender), html=html, recipients=[oneEmail]))
